package com.example.test.comutil;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import com.example.test.R;
import com.puty.conputyutils.common.PutyUtilsConst;

import java.util.regex.Pattern;

/**
 * Created by yue on 2016/4/14.
 */
public class StringUtils {
    private static final String TAG = "StringUtils";

    public static boolean isEnglish(String charaString) {
        return charaString.matches("^[a-zA-Z]*");
    }

    public static boolean isInteger(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        } else {
            return str.matches("-?[0-9]+(\\.[0-9]+)?");
        }
    }

    /**
     * 是否包含高棉文
     *
     * @param
     * @return
     */
    public static boolean textContainsKhmer(String text) {
        for (char charac : text.toCharArray()) {
            if (Character.UnicodeBlock.of(charac) == Character.UnicodeBlock.KHMER) {
                return true;
            }
        }
        return false;
    }

    /**
     * JSON字符串特殊字符处理，比如：“\A1;1300”
     *
     * @param s
     * @return String
     */
    public static String JsonFormat(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '\"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }

    public static int getS2I(String s2) {
        if (TextUtils.isEmpty(s2)) {
            return 0;
        }
        String s = s2.replaceAll(" ", "");
        boolean flag = false;
        if (TextUtils.isEmpty(s) || (!StringUtils.numberValidate(s))) {
            s = "0";
        }
        /*if(s.startsWith("-")){
            flag = true;
            s = s.substring(1,s.length());
        }*/
        if (s.contains("-")) {
            flag = true;
            s = s.replaceAll("-", "");
        }

        int i = Float.valueOf(s).intValue();
        if (flag) {
            i = -i;
        }
        return i;
    }

    public static Float getS2F(String s2, boolean abs) {
        if (TextUtils.isEmpty(s2)) {
            return 0f;
        }
        String s = s2.replaceAll(" ", "");
        boolean flag = false;
        if (TextUtils.isEmpty(s) || (!StringUtils.numberValidate(s))) {
            s = "0";
        }
        /*if(s.startsWith("-")){
            flag = true;
            s = s.substring(1,s.length());
        }*/
        if (s.contains("-")) {
            flag = true;
            s = s.replaceAll("-", "");
        }

        float f = Float.valueOf(s);
        if (flag && (!abs)) {
            f = -f;
        }
        return f;
    }

    public static int getS2I2(String s2) {
        if (TextUtils.isEmpty(s2)) {
            return 0;
        }
        String s = s2.replaceAll(" ", "");
        boolean flag = false;
        if (TextUtils.isEmpty(s) || (!StringUtils.numberValidate(s))) {
            s = "1";
        }
        /*if(s.startsWith("-")){
            flag = true;
            s = s.substring(1,s.length());
        }*/
        if (s.contains("-")) {
            flag = true;
            s = s.replaceAll("-", "");
        }

        int i = Float.valueOf(s).intValue();
        if (flag) {
            i = -i;
        }
        return i;
    }

    public static boolean numberValidate(String str) {
        String regex = "^[\\d.-]+$";
        boolean b = regex(regex, str);
        return b;
    }

    public static boolean regex(String regex, String str) {
        boolean flag = false;
        try {
            Pattern pattern = Pattern.compile(regex);
            flag = pattern.matcher(str).matches();
        } catch (Exception e) {
            LogUtils.e(TAG, "regex e:" + e);
        }
        return flag;

    }

    public static boolean intValidate(String str) {
        String regex = "^[\\d-]+$";
        boolean b = regex(regex, str);
        return b;
    }

    public static boolean floatStringValidate(String str) {
        String regex = "^[-0-9]+(.[0-9]+)?$";
        boolean b = regex(regex, str);
        return b;
    }
    public static boolean cValidate(String str) {
        String regex = "^[\\d-.]+$";
        boolean b = regex(regex, str);
        return b;
    }
    public static void etFilter(EditText et) {
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }


            @Override
            public void afterTextChanged(Editable s) {
                String str = et.getText().toString().trim();
                try {
                    if (!TextUtils.isEmpty(str)) {
                    /*if(str.endsWith(".")||str.startsWith("."))
                        str = str.replace(".","");*/
                        String result = "";
                        LogUtils.i("etw", "str1:" + str);
                        str = str.trim();
                        if(str.startsWith("－")){
                          str = str.replace("－","-") ;
                        }
                         if (str.equals("-")) {
                            result = str;
                            LogUtils.i("etw", "result:" + result);
                        } else {
                            if (intValidate(str)) {
                                int i = Integer.valueOf(str);
                                if (i > 10) {
                                    i = 10;
                                } else if (i < -10) {
                                    i = -10;
                                }
                                result = String.valueOf(i);
                            } else {
                                if (floatStringValidate(str)) {
                                    LogUtils.i("etw", "str:" + str);
                                    float f = StringUtils.getS2F(str, false);
                                    LogUtils.i("etw", "f:" + f);
                                    if (f > 10) {
                                        f = 10;
                                        result = String.valueOf(f);
                                    } else if (f < -10) {
                                        f = -10;
                                        result = String.valueOf(f);
                                    } else if (f == 0) {
                                        result = str;
                                    } else {
                                        result = String.valueOf(f);
                                    }

                                } else {
                                    if(cValidate(str)) {
                                        if(str.contains("..")){
                                           str = str.replace("..",".");
                                        }else if(str.contains("...")){
                                            str = str.replace("...",".");
                                        }else if(str.contains("....")){
                                            str = str.replace("....",".");
                                        }
                                        result = str;
                                    }
                                }
                            }
                        }
                        LogUtils.i("etw", "result:" + result);
                        et.removeTextChangedListener(this);
                        et.setText(result);
                        et.setSelection(result.length());
                        et.addTextChangedListener(this);
                    }
                } catch (Exception e) {
                    LogUtils.e("etw", "e:" + e);
                }
            }
        });
    }

    public static boolean isEmojiCharacter(char codePoint) {
               return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                       (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                       ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                       ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
           }

    /**
     * 检验内容是否符合规范，不规范则进行修改
     *
     * @param context 上下文对象
     * @param type 类型
     * @param content 内容
     * @return
     */
    public static String changecontent(Context context, int type, String content) {
        switch (type) {
            case PutyUtilsConst.BFORMAT_TIF25_CODE://TIF25码规范，由数字组成，且长度必须为奇数
                //TIF（Interleaved 2 of 5）是在code 25基础上设计的，这两种格式都使用相同的编码方法，
                // 只不过在ITF格式中条形和空白都承载数据，奇数位用条形编码，偶数位用空白编码。ITF是一种高密度、
                // 长度可变而且只用数字的格式。此条码是航运和仓储行业最常见的格式之一，您最多可在条码向导中输入40位ITF代码必须为数字。
                if (FormatUtil.isNumeric(content)) {
                    if (content.length() % 2 == 1) {//奇数位取全部内容
                        content = "0" + content;
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showToast(context.getString(R.string.bzcywmgs));
                            }
                        });
                    }

                } else {
                    content = "12345670";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //"输入内容不符合TIF25码规范,应只由数字组成"
                            ToastUtils.showToast(context.getResources().getString(R.string.neb_tif25));
                        }
                    });
                }
                break;
            case PutyUtilsConst.BFORMAT_39_CODE://39
                if (!FormatUtil.isRegular(content, "^[A-Za-z0-9 \\+\\-*/%\\$\\.]+$")) {
                    content = "12345678";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showToast(context.getString(R.string.bzcywmgs));
                        }
                    });
                }
                break;
            case PutyUtilsConst.BFORMAT_DEFAULT_CODE:
            case PutyUtilsConst.BFORMAT_128_CODE://128
                if (!FormatUtil.isRegular(content, "^[\\x00-\\x7f]+$")) {
                    content = "12345678";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showToast(context.getString(R.string.bzcywmgs));
                        }
                    });
                }
                break;
            case PutyUtilsConst.BFORMAT_KUDBAR_CODE://库德巴码
                if (!FormatUtil.isRegular(content, "^[A-D]+[0-9A-D\\-\\:\\/\\.\\+\\$]+[A-D]+$")) {
                    content = "A12345A";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showToast(context.getString(R.string.bzcywmgs));
                        }
                    });
                }
                break;
            case PutyUtilsConst.BFORMAT_EAN_8_CODE://EAN_8码校验码规则与EAN_13一样，但其前面加5个零，即奇数位变偶数位，偶数位变奇数位
                content = interceptData(context, content, 7, R.string.neb_ean8_7);
                if (FormatUtil.isNumeric(content)) {
                    //奇数     //偶数
                    int one = 0;
                    int two = 0;
                    for (int i = 1; i < 8; i++) {
                        if (i % 2 == 1) {//奇偶位互换
                            two = two + Integer.valueOf(content.substring(i - 1, i));
                        } else {
                            one = one + Integer.valueOf(content.substring(i - 1, i));
                        }
                    }
                    String num = String.valueOf((10 - (one + two * 3) % 10) % 10);//有可能校验码为10，则效验码为0
                    content = content + num;
                } else {
                    content = "12345672";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //"输入内容不符合EAN_8码规范,应只由数字组成"
                            ToastUtils.showToast(context.getResources().getString(R.string.neb_ean8));
                        }
                    });
                }
                break;
            case PutyUtilsConst.BFORMAT_EAN_13_CODE://EAN_13码
                content = interceptData(context, content, 12, R.string.neb_ean13_12);
                if (FormatUtil.isNumeric(content)) {
                    //奇数     //偶数
                    int one = 0;
                    int two = 0;
                    for (int i = 1; i < 13; i++) {
                        if (i % 2 == 1) {
                            one = one + Integer.valueOf(content.substring(i - 1, i));
                        } else {
                            two = two + Integer.valueOf(content.substring(i - 1, i));
                        }
                    }
                    String num = String.valueOf((10 - (one + two * 3) % 10) % 10);
                    content = content + num;
                } else {
                    content = "1234567890128";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //"输入内容不符合EAN_13码规范,应只由数字组成"
                            ToastUtils.showToast(context.getResources().getString(R.string.neb_ean13));
                        }
                    });
                }
                break;
            case PutyUtilsConst.BFORMAT_UPC_CODE://UPC码
                content = interceptData(context, content, 11, R.string.neb_upc_11);
                if (FormatUtil.isNumeric(content)) {
                    //奇数     //偶数
                    int one = 0;
                    int two = 0;
                    for (int i = 1; i < 12; i++) {
                        if (i % 2 == 1) {
                            one = one + Integer.valueOf(content.substring(i - 1, i));
                        } else {
                            two = two + Integer.valueOf(content.substring(i - 1, i));
                        }
                    }
                    String num = String.valueOf((10 - (one * 3 + two) % 10) % 10);
                    content = content + num;
                } else {
                    content = "123456789012";
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //"输入内容不符合UPC码规范,应只由数字组成"
                            ToastUtils.showToast(context.getResources().getString(R.string.neb_upc));
                        }
                    });
                }
                break;
        }
        return content;
    }

    /**
     * 补全及截取数据
     *
     * @param context 上下文对象
     * @param content 内容
     * @param len 长度
     * @param toastId 提示消息id
     * @return
     */
    public static String interceptData(Context context, String content, int len, int toastId) {//
        if (content.length() < len) {
            for (int i = content.length(); i < len; i++) {
                content += "0";
            }
            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast(context.getString(toastId));
                }
            });
        } else if (content.length() >= len) {
            content = content.substring(0, len);
        }
        return content;
    }
}
